﻿var filesHtml = {};
var loanItems;
var url = new Url();
var $userId = url.GetQueryString("userId");
var $orderId = url.GetQueryString("orderId");
var serializer = new JSONSerializer();


var idCard;

$(function () {
    //页面元素隐藏与显示，判断批核信息是否显示
    if ($("#displayMode").attr("data-total") === "True" || $("#displayMode").attr("data-reconsider") === "True") {
        $("#provInfo").css("display", "inline");
    }
    //var $index = $('#displayMode').attr('data-index');
    //for (var i = 0; i < $index; i++) {
    //    $(".verifyOpinion:eq('" + i + "')").css("display", "inline").find("textarea").attr("disabled", "disabled");
    //}

    //$(".verifyOpinion:eq('" + $index + "')").css("display", "inline");
    //加载数据
    $.getJSON("../Handler/LoanProductOrderHandler.ashx",
        { Type: 4, OrderId: $orderId, _: Math.random() },
        function (result) {
            if (result.Status) {
                updateProgress(result.Data);
                loanItems = result.Data.LoanItems;
                if (result.Data.Verify) {
                    $("#workContactOpinion").val(result.Data.Verify.WorkContactOpinion);
                    $("#familyContactOpinion").val(result.Data.Verify.FamilyContactOpinion);
                    $("#emergContactOpinion").val(result.Data.Verify.EmergContactOpinion);
                    $.each(result.Data.Verify.result, function (index, item) {
                        $(".verifyOpinion:eq('" + item.Index + "')").css("display", "inline")
                                                                    .find("textarea").val(item.AuditOpinion);
                    });
                }
                loadVerifyFiles(result.Data.Order.ProductTypeId);
                if (result.Data.Order) {
                    serializer.DeSerializeToSpan($(".orderInfo"), result.Data.Order);
                    //单独绑定申请借款种类
                    //var productType = result.Data.Order.IsAccordanceProduct ? result.Data.Order.ChangeProductName.split(',')[0] : result.Data.Order.productName;
                    //$("em[data-name='Product']").text(productType);

                    serializer.DeSerializeToSpan($("#orderData"), result.Data.Order);
                    //根据月还款额判断是否存在批核信息
                    var repayPerMonth = $("span[data-name=RepayPerMonth]").text();
                    if (repayPerMonth == "") {
                        $("#provInfo").css("display", "none");
                    }
                    else {
                        //单独绑定是否更换产品名称
                        $("div.isAccordanceProduct>span").text(result.Data.Order.IsAccordanceProduct ? "是" : "否");
                        if (result.Data.Order.IsAccordanceProduct) {
                            $("div.accordanceProduct").css("display", "block")
                                .children("span").text(result.Data.Order.ChangeProductName.split(',')[0]);
                        }
                        //单独绑定是否联名借款
                        $("div.isCoborrowLoan>span").text(result.Data.Order.IsCoborrowLoan ? "是" : "否");
                        if (result.Data.Order.IsCoborrowLoan) {
                            $("div.coborrowLoan").css("display", "block");
                            $("div.coborrowLoan>span").text(result.Data.Order.CoborrowName.split(',')[0]);
                        }
                    }
                }
                serializer.DeSerializeToSpan($(".userInfo"), result.Data.User);
                idCard = result.Data.User.IDCard;
                serializer.DeSerializeToSpan($(".workInfo"), result.Data.Work);
                serializer.DeSerializeToSpan($(".familyInfo"), result.Data.Family);
                $("em[data-name='WorkEmail']").text(result.Data.Work.WorkEmail);
                $("em[data-name='IsHaveChildValue']").text(result.Data.Family.IsHaveChildValue);
                $("em[data-name='MaritalStatusValue']").text(result.Data.Family.MaritalStatusValue);
                $("em[data-name='HousePropertyValue']").text(result.Data.Family.HousePropertyValue);
                //加载文件信息
                $.each(result.Data.LoanItems, function (index, item) {
                    $("#FileTemplate").tmpl(item.Files).appendTo($("#fileContent"));
                    filesHtml["content" + item.AuthId] = $("#fileContent").html();
                    $("#fileContent").empty();
                });
            } else {
                alert(result.Message);
            }
        });

    var LoadRelationInfo = function () { };
    LoadRelationInfo.prototype = {

        Url: "",
        Data: {},
        type: 0,
        CallBack: null,
        GetRelationInfo: function () {
            $this = this;
            this.Data.type = this.type;
            this.Data._ = Math.random();
            $.ajax({
                type: "post",
                dataType: "json",
                data: this.Data,
                url: this.Url,
                async: false,
                cache: false,
                complete: function () { },
                success: function (result) {
                    if (result.Status) {
                        if ($this.CallBack) {
                            $this.CallBack(result.Data);
                        }
                    }
                    else {
                        alert(result.Message);
                    }
                }
            });
        },
    };
    var loadinfo = new LoadRelationInfo();
    loadinfo.Data = { OrderId: $orderId };

    //预加载银行流水信息（必须首次就加载出来）
    loadinfo.Url = "../Handler/LoanBankRunningHandler.ashx";
    loadinfo.type = 1;
    loadinfo.CallBack = function (data) {
        if (data != null) {
            $.each(data, function (index, item) {
                if (item.Seq.indexOf("totalFlow") < 0 && item.Seq.indexOf("avgFlow") < 0) {
                    $("#FlowTemplate").tmpl().insertBefore($("#trFlowTotal"));
                    new JSONSerializer().DeSerialize($("tr.rowFlow:last"), item);
                }
                else if (item.Seq.indexOf("avgFlow") < 0) { //单独绑定总计信息
                    $("#txtAccount1Total").text(item.Salary);
                    $("#txtAccount2Total").text(item.Bonus);
                    $("#txtAccount3Total").text(item.Personal);
                    $("#txtAccount4Total").text(item.ForPublic);
                    $("#flowOther").val(item.Other);
                }
                else {//单独绑定月均信息
                    $("#txtAccount1Avg").text(item.Salary);
                    $("#txtAccount2Avg").text(item.Bonus);
                    $("#txtAccount3Avg").text(item.Personal);
                    $("#txtAccount4Avg").text(item.ForPublic);
                }
            })
        }
    };
    loadinfo.GetRelationInfo();

    var ISLOAD = false;//标识符 用于标识关联信息是否被预加载
    //点击TAB（批核信息）预加载各类关联信息
    $("#procInfo").click(function () {
        if (!ISLOAD) {
            //预加载申请人照会信息
            loadinfo.Url = "../Handler/LoanReplyNoteHandler.ashx";
            loadinfo.type = 1;
            loadinfo.CallBack = function (data) {
                if (data != null) {
                    //$("textarea[name=LoanReplyMemo]").val(decodeURI(data.LoanReplyMemo));
                    editor.html(decodeURI(data.LoanReplyMemo));
                    new JSONSerializer().DeSerialize($("#tblNode"), data);
                }
            };
            loadinfo.GetRelationInfo();

            //预加载企业信息
            loadinfo.Url = "../Handler/CompanyInfoHandler.ashx";
            loadinfo.type = 1;
            loadinfo.CallBack = function (data) {
                if (data != null) {
                    new JSONSerializer().DeSerialize($("#tblBussiness"), data);
                    //单独处理成立时间
                    $("input[name=FoundingTime]").val(ChangeDateFormat(data.FoundingTime));
                }
            };
            loadinfo.GetRelationInfo();

            //预加载信用卡信息
            loadinfo.Url = "../Handler/LoanCreditCardHandler.ashx";
            loadinfo.type = 1;
            loadinfo.CallBack = function (data) {
                if (data != null) {
                    $.each(data, function (index, item) {
                        if (item.Seq.indexOf("总计") < 0) {
                            $("#CridetTemplate").tmpl().insertBefore($("#trCridetTotal"));
                            new JSONSerializer().DeSerialize($("tr.rowCridet:last"), item);
                        }
                        else { //单独绑定总计信息
                            $("#txtCridetTotal").text(item.LineCredit);
                            $("#txtOverDraftTotal").text(item.Overdraft);
                            $("#txtOverdueCountTotal").text(item.OverdueCount);
                            $("#inputOther").val(item.Other);
                        }
                    })
                }
            };
            loadinfo.GetRelationInfo();

            //预加载借款情况信息
            loadinfo.Url = "../Handler/LoanInfoHandler.ashx";
            loadinfo.type = 1;
            loadinfo.CallBack = function (data) {
                if (data != null) {
                    $.each(data, function (index, item) {
                        if (item.Seq.indexOf("total") < 0) {
                            $("#LoanTemplate").tmpl().insertBefore($("#trLoanTotal"));
                            new JSONSerializer().DeSerialize($("tr.rowLoan:last"), item);
                            //单独绑定到期日
                            $("tr.rowLoan:last").find("input[name=DueDate]").val(ChangeDateFormat(item.DueDate));
                        }
                        else { //单独绑定总计信息
                            $("#txtLoanTotal").text(item.Total);
                            $("#txtBanlanceTotal").text(item.Balance);
                            $("#txtPerRepayTotal").text(item.RepayPerMonth);
                            $("#loanOther").val(item.Other);
                        }
                    })
                }
            };
            loadinfo.GetRelationInfo();



            //预加载客户过往记录信息
            loadinfo.Url = "../Handler/LoanProductOrderHandler.ashx";
            loadinfo.type = 24;
            loadinfo.Data.OrderId = $orderId;
            loadinfo.Data.IDCard = idCard;
            loadinfo.CallBack = function (data) {
                if (data != null) {
                    $.each(data, function (index, item) {
                        $("#CustomRecordTemplate").tmpl(item).appendTo("#tbRecord");
                    })
                }
            };
            loadinfo.GetRelationInfo();

            //查看页面不能编辑 ReadOnly
            //申请人照会信息
            $(".saveNode").css("display", "none");
            $("#tblNode input,#tblNode textarea").attr("readonly", true);

            //信用卡信息
            $(".btnAddCridet,.btnDelCridet,.btnSaveCridet").css("display", "none");
            $("#tbCridet input").attr("readonly", true);


            //借款情况信息
            $(".btnAddLoan,.btnDelLoan,.btnSaveLoan").css("display", "none");
            $("#tbLoan input").attr("readonly", true);

            //企业信息
            $(".saveBusiness").css("display", "none");
            $("#tblBussiness input").attr("readonly", true);

            //银行流水信息
            $(".btnAddFlow,.btnDelFlow,.btnSaveFlow").css("display", "none");
            $("#tbFlow input").attr("readonly", true);
            ISLOAD = true;
        }
    });

});



//更新进度条
function updateProgress(data) {
    var total = 0, count = 5;
    if (data.Order) {
        total += 100 / count;
    }
    if (data.Family) {
        total += 100 / count;
    }
    if (data.User) {
        total += 100 / count;
    }
    if (data.Work) {
        total += 100 / count;
    }
    if (data.LoanItems && data.LoanItems.length > 0) {
        total += 100 / count;
    }
    total = parseInt(total);
    $(".progressBar").text(total + "%").css("width", total + "%");
}

//加载审核文件项目
function loadVerifyFiles(productId) {
    $.getJSON("../Handler/ProductHandler.ashx",
        { Id: productId, Type: 5 },
        function (result) {
            if (result.Status) {
                $("#verifyList").empty();
                $.each(result.Data, function (index, item) {
                    $("#AuthentionTemplate").tmpl(item).appendTo("#verifyList").find(".openLayout").click(function () {
                        $("#fileOpinion").val("");
                        var authId = $(this).attr("data-authid");
                        $("#authId").val(authId);
                        $("#itemId").val($(this).attr("data-itemid"));
                        $("#filelist").empty();
                        $("#filelist").html(filesHtml["content" + authId]);
                        loadZoomScript();
                        $("#fileOpinion").hide().empty();
                        if ($("#displayMode").attr("data-disabled") === "False" && !$(this).attr("data-passed")) {
                            $("#backFile,#passFile").show();
                        } else {
                            $("#backFile,#passFile").hide();
                        }
                    });
                });
                updateItemsStatus();
            } else {
                alert(result.Message);
            }
        });
}
//添加预览脚本
function loadZoomScript() {
    $("#zoomScript").remove();
    $("#zoom").remove();
    var myScript = document.createElement("script");
    myScript.type = "text/javascript";
    myScript.id = "zoomScript";
    myScript.src = "../Plugins/gurdeZoom/js/zoom.min.js";
    document.body.appendChild(myScript);
}
//更新审核信息
function updateItemsStatus() {
    $.each(loanItems, function (index, item) {
        var dom = $("#verifyList div[data-authid='" + item.AuthId + "']");
        if (dom) {
            dom.attr("uploaded", true);
            dom.find(".openLayout").attr("data-itemid", item.LoanItemId);
            if (filesHtml.hasOwnProperty("content" + item.AuthId)) {
                var matches = filesHtml["content" + item.AuthId].match(/src=\"(.*?)\"/);
                if (matches) {
                    dom.find(".uploadStatus").text("资料已上传").end().find(".openLayout").show();
                    if (item.Passed) {
                        dom.find(".verifyStatus").text("已通过审核").end().find(".openLayout").attr("data-verified", true);
                    }
                    else {
                        if (item.VerifyOpinion != "" && item.VerifyOpinion != null) {
                            dom.find(".verifyStatus").text("审核未通过").end().find(".openLayout").attr("data-verified", false);
                        }
                    }
                }
            }
        }
    });
    $("#verifyList").children("div[data-required='false']:not('[uploaded]')").remove();
}

//格式化日期
function ChangeDateFormat(cellval) {
    var date = new Date(parseInt(cellval.replace("/Date(", "").replace(")/", ""), 10));
    var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
    var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    return date.getFullYear() + "-" + month + "-" + currentDate;
}